<template>
  <div class="form-limit">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="上传数据：" :required="true">
        <mine-upload
          ref="upload"
          :fileType="accept"
          @change="onChange"
        ></mine-upload>
        <div class="text-left margin-bottom-10">
          <mine-button
            secondary
            size="mini"
            @click="downloadFile"
            :disabled="!projectType"
            :loading="downloading"
            >下载模板<i class="iconfont icon-download-line is-right"></i
          ></mine-button>
        </div>
      </el-form-item>
      <el-form-item label="数据集名称：" prop="fileName">
        <el-input
          v-model="form.fileName"
          placeholder="请输入数据集名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="数据集描述：" prop="fileDesc">
        <el-input
          type="textarea"
          v-model.trim="form.fileDesc"
          :autosize="{ minRows: 5, maxRows: 10 }"
          placeholder="请输入数据集描述"
          showMaxLimit
          :maxlength="200"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  props: {
    projectType: {
      type: String,
      default: "",
    },
  },
  computed: {
    accept() {
      if (this.projectType === "") {
        return ".txt,.csv,.xls,.xlsx,.zip";
      } else if (
        ["data_predict", "txt_classify", "data_unsupervised"].includes(
          this.projectType
        )
      ) {
        return ".txt,.csv,.xls,.xlsx";
      } else if (
        ["img_classify", "voice_classify", "img_detection"].includes(
          this.projectType
        )
      ) {
        return ".zip";
      }
      return ".txt,.csv,.xls,.xlsx,.zip";
    },
  },
  data() {
    return {
      form: {
        fileName: "",
        fileDesc: "",
        file: "",
        creater: this.$store.state.userName,
      },
      rules: {
        fileName: {
          required: true,
          message: "请输入数据集名称",
          trigger: "blur",
        },
        fileDesc: {
          required: true,
          message: "请输入数据集描述",
          trigger: "blur",
        },
      },
      fileList: [],
      downloading: false,
    };
  },
  methods: {
    onChange(data) {
      this.form.file =
        data.fileList && data.fileList.length ? data.fileList[0] : "";
      this.fileList =
        data.fileList && data.fileList.length ? data.fileList : [];
    },
    async downloadFile() {
      this.downloading = true;
      try {
        let res = null;
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/material-info/getUrl?projectType=${_self.projectType}`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {
                  // projectType: _self.projectType,
                },
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.$message.success("下载成功");
                // _self.close();
              } else {
                _self.$message.error(result.msg);
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/material-info/getUrl?projectType=${this.projectType}`,
            "post",
            "application/json;charset=UTF-8",
            {},
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.success) {
                this.$message.success("下载成功");
                // this.close();
              } else {
                this.$message.error(res.msg);
              }
            },
            { once: true }
          );
        } else {
          await this.$store.dispatch("dataAdminMaterialInfoGetUrl", {
            projectType: this.projectType,
          });
        }
      } catch (e) {
        console.error(e);
      }
      this.downloading = false;
    },
    submit() {
      if (!this.$common.doSubmit("form", this)) return;
      if (!this.fileList.length) {
        this.$message({ type: "warning", message: "请上传数据文件" });
        return;
      }
      return this.form;
    },
  },
};
</script>
<style lang="less" scoped></style>
